import 'package:flutter/material.dart';

import '../model/tab_info_model.dart';
import '../tool/public_tool.dart';
import 'page_notifier.dart';

/// FileName tab_notifier
///
/// @Author lax
/// @Date 2023/5/10
///
/// @Description tab通知器

class TabNotifier extends PageNotifier {
  /// allTabInfo里需要显示的tab下标，用,拼接（如'0,1,3') 不要有空格
  /// 默认为null，不设置则全部显示
  final String? showIndexes;

  /// 初始化tab下标
  final int? initialIndex;

  /// 显示的tab数据源
  List<TabModel> dataSource = [];

  late TabController controller;

  final TickerProvider provider;

  /// 当前选中的tab
  TabModel? get currentTabModel {
    if (controller.index >= 0 && controller.index < dataSource.length) {
      return dataSource[controller.index];
    }
    return null;
  }

  TabNotifier({
    this.showIndexes,
    this.initialIndex,
    required this.provider,
    List<TabModel>? dataSource,
  }) {
    reloadDataSource(dataSource);
  }

  /// 重新加载数据源
  void reloadDataSource(List<TabModel>? data) {
    final list = data ?? [];

    if (stringIsEmpty(showIndexes)) {
      dataSource = list;
    } else {
      final indexList = showIndexes?.split(',') ?? [];
      dataSource = list
          .where((element) =>
          indexList.contains(list.indexOf(element).toString()))
          .toList();
    }

    controller = TabController(
      initialIndex: initialIndex ?? 0,
      length: dataSource.length,
      vsync: provider,
    );
    notifyListeners();
  }
}
